package com.one.controller;


import com.one.dto.*;
import com.one.entity.Statistics;
import com.one.service.IStatisticsService;
import com.one.utils.WordUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/statistics")
@Api(tags = "监测数据统计")
public class StatisticsController {

	@Autowired
	private IStatisticsService statisticsService;
	
	/********************* nepg工程 *********************/
	@PostMapping("/saveStatistics")
	@ApiOperation(value = "保存一条监测信息")
	public int saveStatistics(@RequestBody Statistics statistics) {
		log.info("保存一条监测信息请求：{}",statistics);
		return statisticsService.saveStatistics(statistics);
	}
	/********************* nepg工程 *********************/
	
	/********************* nepm工程 *********************/
	@PostMapping("/listStatisticsPage")
	@ApiOperation(value = "监测数据分页查询")
	public PageResponseDto<Statistics> listStatisticsPage(@RequestBody StatisticsPageRequestDto statisticsPageRequestDto) {
		log.info("监测数据分页查询请求：{}",statisticsPageRequestDto);
		return statisticsService.listStatisticsPage(statisticsPageRequestDto);
	}
	
	@PostMapping("/getStatisticsById")
	@ApiOperation(value = "根据ID获取监测数据")
	public Statistics getStatisticsById(@RequestBody Statistics statistics) {
		log.info("根据ID获取监测数据：{}",statistics);
		return statisticsService.getStatisticsById(statistics.getId());
	}
	/********************* nepm工程 *********************/
	
	/********************* nepv工程 *********************/
	@RequestMapping("/listProvinceItemTotalStatis")
	@ApiOperation(value = "按省分组获取监测数据")
	public List<ProvinceItemTotalStatisDto> listProvinceItemTotalStatis() {
		log.info("按省分组获取监测数据：");
		return statisticsService.listProvinceItemTotalStatis();
	}
	
	@PostMapping("/listAqiDistributeTotalStatis")
	@ApiOperation(value = "按api指标级别获取监测数据总数")
	public List<AqiDistributeTotalStatisDto> listAqiDistributeTotalStatis() {
		log.info("按api指标级别获取监测数据总数请求");
		return statisticsService.listAqiDistributeTotalStatis();
	}

	@GetMapping("/listAqiTrendTotalStatis")  // 改为 GET 请求
	@ApiOperation(value = "获取year年份的所有api指标趋势监测数据总数")
	public List<AqiTrendTotalStatisDto> listAqiTrendTotalStatis(@RequestParam Integer year) {
		log.info("获取{}年份的所有api指标趋势监测数据总数", year);
		return statisticsService.listAqiTrendTotalStatis(year);
	}
	
	@PostMapping("/getAqiCount")
	@ApiOperation(value = "获取监测数据总数")
	public long getAqiCount() {
		log.info("获取监测数据总数请求：{}");
		return statisticsService.getAqiCount();
	}
	
	@PostMapping("/getAqiGoodCount")
	@ApiOperation(value = "获取监测结果显示好的数据总数")
	public long getAqiGoodCount() {
		log.info("获取监测结果显示好的数据总数：{}");
		return statisticsService.getAqiGoodCount();
	}
	
	@PostMapping("/getProvinceCoverage")
	@ApiOperation(value = "获取监测数据的省覆盖率")
	public String getProvinceCoverage() {
		log.info("获取监测数据的省覆盖率：{}");
		return statisticsService.getProvinceCoverage();
	}
	
	@PostMapping("/getCityCoverage")
	@ApiOperation(value = "获取监测数据的城市覆盖率")
	public String getCityCoverage() {
		log.info("获取监测数据的城市覆盖率：{}");
		return statisticsService.getCityCoverage();
	}
	@GetMapping("/report")
	@ApiOperation(value = "获取年度报告")
	public void generateReport(@RequestParam String year, HttpServletResponse response)throws IOException{
		//1.准备数据
		Map<String,Object> dataMap=new HashMap<>();
		dataMap.put("year",year);
		long totalNum=statisticsService.getApiCountByYear(year);
		dataMap.put("totalNum",totalNum);//计算某年的总共api监测数据totalNum
		String goodRate=String.format("%.1f",statisticsService.getAqiGoodCountByYear(year)*1.0/totalNum*100);
		dataMap.put("goodRate",goodRate);//计算某年空气质量优良监测数据项goodRate
		List<ProvinceItemTotalStatisDto> proList=statisticsService.listProvinceTotalStatisByYear(year);//计算某年aqi中数目排名第一、第二（firstPro、firstNum、firstRate;secondPro、secondNum、secondRate）
		dataMap.put("firstPro",proList.get(0).getProvinceName());
		Integer firstNum=proList.get(0).getAqiTotal();
		dataMap.put("firstNum",firstNum);
		String firstRate=String.format("%.1f",firstNum*1.0/totalNum*100);
		dataMap.put("firstRate",firstRate);
		dataMap.put("secondPro",proList.get(1).getProvinceName());
		Integer secondNum=proList.get(1).getAqiTotal();
		dataMap.put("secondNum",secondNum);
		String secondRate=String.format("%.1f",secondNum*1.0/totalNum*100);
		dataMap.put("secondRate",secondRate);
		List<ProvinceItemTotalStatisDto> proBadList=statisticsService.listProvinceBadTotalStatisByYear(year);//计算某年各省份监测数据中aqi超标累计以及排名前三的省份（badFirstPro、badSecondPro、badThirdPro、data）
		dataMap.put("badFirstPro",proBadList.get(0).getProvinceName());
		dataMap.put("badSecondPro",proBadList.get(1).getProvinceName());
		dataMap.put("badThirdPro",proBadList.get(2).getProvinceName());
	    List<Map<String,Object>> list=new ArrayList<>();
		for (int i=0;i<proBadList.size();i++){
			Map<String,Object> data=new HashMap<>();
			data.put("index",i+1);
			data.put("shortPro",proBadList.get(i).getProvinceAbbr());
			data.put("pro",proBadList.get(i).getProvinceName());
			data.put("aqiBadNum",proBadList.get(i).getAqiTotal());
			list.add(data);
		}
		dataMap.put("proList",list);
		//2.输出word报告
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
		configuration.setDefaultEncoding("UTF-8");
		configuration.setClassForTemplateLoading(this.getClass(), "/templates"); //模版加载目录设置
		Template template = null;
		try {
			template = configuration.getTemplate(WordUtil.TEMPLATE);//模板名称
		} catch (IOException e) {
			e.printStackTrace();
		}
		String docxFileName = UUID.randomUUID().toString().replaceAll("-","")+"_"+year+"年"+ WordUtil.DOCXFILEPEX;//输出文件名称
		String docxFilePath=WordUtil.WINDOWSDOCUMENT+"/"+docxFileName;//输出文件路
		File directory = new File(WordUtil.WINDOWSDOCUMENT);
		if (!directory.exists()) {
			 directory.mkdirs(); // 创建目录及其所有必需的父目录
		}
		try {
			BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docxFilePath)));
			template.process(dataMap, writer);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 设置响应头，告诉浏览器这是一个文件下载
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + docxFilePath.substring(docxFilePath.lastIndexOf('/') + 1) + "\"");

		// 设置文件类型
		response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

		// 读取文件并写入响应输出流
		Files.copy(java.nio.file.Paths.get(docxFilePath), response.getOutputStream());
	}
	/********************* nepv工程 *********************/
}
